/*
 * Class Grid
 */
Grid.prototype = new Element();
Grid.prototype.constructor = Element;

Grid.prototype.dick = "dick";

Grid.prototype.ACTION_NAMES = {
    SEARCH_SELECT:{name:'queryField', id:'rck-grid-select-'},
    SEARCH_INPUT:{name:'queryValue', id:'rck-grid-input-'}
};

Grid.prototype.title = '';

Grid.prototype.proxy = {};
Grid.prototype.rows = [];
//almacena array con datos por id generado
Grid.prototype._items = [];
//almacena columnas por indice name
Grid.prototype._columns = [];
Grid.prototype.autoLoad = false;
Grid.prototype.remoteSort = false;
Grid.prototype.url = '';
Grid.prototype.fit = false;

Grid.prototype._minTdWidth = 100;

Grid.prototype._tdWidth = 0;

Grid.prototype.page = 1;
Grid.prototype.rp = 200;
Grid.prototype.total = 0;
Grid.prototype.sortname = '';
Grid.prototype.sortorder = '';
Grid.prototype.queryValue= '';
Grid.prototype.queryField= '';
Grid.prototype.searchButtonText= 'Buscar';

Grid.prototype.searchItems= [];//array [{field:'columnName', display:'Nombre persona'}]

Grid.prototype.columns= [];//array [{display: 'SectorId',name: 'SectorId',hide:true, width:'10',sortable:true},]

Grid.prototype._isInner = false;
Grid.prototype._parent = {};

Grid.prototype.defaultClass = 'table table-bordered table-hover';
/*
 * build the thead of table grid
 */

//get the search ID attribute of object query (select, input...)
Grid.prototype._getSearchID = function(object){
    switch(object){
        case 'select':return this.ACTION_NAMES.SEARCH_SELECT.id+this.id;
        case 'input':return this.ACTION_NAMES.SEARCH_INPUT.id+this.id;
    }
}
//get the search name attribute of object query (select, input...)
Grid.prototype._getSearchName = function(object){
    switch(object){
        case 'select':return this.ACTION_NAMES.SEARCH_SELECT.name;
        case 'input':return this.ACTION_NAMES.SEARCH_INPUT.name;
    }
}

Grid.prototype.makeHtml = function(){
    
    this.Classes.push(this.CLASSNAMES.GRID);
    this.Classes.push(this.defaultClass);
    
    if(this.width.indexOf('%') == -1){
        this.width = parseInt(this.width)+"px";
    }
    var theader = this._getHeaderHtml();
    var tbody = this._getBodyHtml();
    
    
    return '<div id="'+this.id+'" style="width:'+this.width+';">'+theader+tbody+'</div>';
}

Grid.prototype._load = function(callback){
    new Request({
        method:'GET',
        url:this.url,
        data:{
            sort:{field:this.sortname, direction:this.sortorder},
            query:{field:this.queryField, value:this.queryValue},
            page:this.page,
            rp:this.rp,
            _dt:(new Date()).getTime()
        },
        success:function(data){
            callback(data.data)
        }
    });
};

Grid.prototype.setData = function(){
    var trs = '';
    var td = '';
    var row = "";
    var _this = this;
    
    //clean old data
    jQuery(this.jID()+" table tbody").html('');
    
    if(this.total>0 && this.rows.length>0){
        for(var i=0;i<_this.rp;i++){
            var trId = _this.makeUId();
            _this._items[trId] = _this.rows[i];
            tr = '<tr id="'+trId+'">';
            td = '';
            row = _this.rows[i];//{id:1, name: 'name', c1:20}
            jQuery.each(_this.columns, function(k, item){
                td = td+"<td>"+row[item.name]+"</td>";
            })
            trs = trs+tr+td+'</tr>';
        }
    }
    else{
        for(i=0;i<this.rp;i++){
            td = '';
            for(k=0;k<this.columns.length;k++)
                td = td+"<td style='height:25px;'>&nbsp;</td>";
            trs = trs+"<tr>"+td+"</tr>";
        }
    }
    //set new data
    jQuery(this.jID()+" table tbody").html(trs);
    //fix grid width and cells
    jQuery(this.jID()+" table tbody tr td").css('width', this._tdWidth);
}

Grid.prototype.sort = function(column, direction, call){
    var _this = this;
    if(this.remoteSort)
        console.log('GET SERVER : ordenar por columna: '+column+", direction: "+direction);
    else
        console.log('LOCAL : ordenar por columna: '+column+", direction: "+direction);
    this._load(function(data){
        _this.rows = data.rows;
        _this.total = data.total;
        //ya existen filas
        if(jQuery(_this.jID()+" table tbody tr").length>0){
            console.log('to set data')
            _this.setData();
        }
        
    });
}


Grid.prototype._getBodyHtml = function(){
    var classes = this._getClassesString();
    
    
    var total = this.total;
    var _this = this;
    var trs = '';
    var td = '';
    var row = '';
    var i=0;
    
//    var tdwidth = this.columns
    
    if(this.rows && this.rows.length>0){
        for(i=0;i<this.rp;i++){
            var trId = this.makeUId();
            this._items[trId] = this.rows[i];
            tr = '<tr id="'+trId+'">';
            td = '';
            row = this.rows[i];//{id:1, name: 'name', c1:20}
            jQuery.each(this._columns, function(i, item){
                td = td+"<td>"+row[i]+"</td>";
            })
            trs = tr+td+'</tr>';
        }
    }
    else{
        var trClass = "odd";
        for(i=0;i<this.rp;i++){
            td = '';
            if(i%2==0)  trClass = 'even';
            else     trClass = 'odd';
            for(k=0;k<this.columns.length;k++)
                td = td+"<td style='height:25px;'>&nbsp;</td>";
            trs = trs+"<tr class='"+trClass+"'>"+td+"</tr>";
        }
    }
    var html = '';
    if(this.height){
        this.height = parseInt(this.height)+"px";
    }
    else    this.height = "200px";
    
//    html = '<table style="width:100%;border-top:none;" class="table table-bordered"><tbody style="height:'+this.height+";"+cssTbody+';">'+trs+'</tbody></table>';
    html = '<table style="width:100%;border-top:none;" class="'+classes+'"><tbody style="height:'+this.height+";"+cssTbody+';">'+trs+'</tbody></table>';
    
    var cssTbody = '';
    if($.browser.msie){
        html = '<div style="height:'+this.height+";"+cssTbody+';overflow-y:scroll;overflow-x:hidden;">'+html+'</div>';
    }
    return html;
    
}

Grid.prototype._getHeaderHtml = function(){
    var classes = this._getClassesString();
    var selectClass = this.CLASSNAMES.GRID_SEARCH_SELECT;
    var inputClass = this._getClassesString([this.CLASSNAMES.GRID_SEARCH_INPUT, 'input-small']);
    var titleClass = this.CLASSNAMES.GRID_TITLE;
    
    var _this = this;
    
    //id,name for select query field
    var sId = this._getSearchID('select');
    var sName = this._getSearchName('select');
    
    //id,name for input query value
    var iId = this._getSearchID('input');
    var iName = this._getSearchName('input');
    
    var select = '';
    var input = '';
    var btnSearch = '';
    var selected = '';
    var search = '';
    var colspan =  1;
    var th = '';
    
    if(this.columns){
        colspan = this.columns.length;
        jQuery.each(_this.columns, function(i, item){
            var thId = _this.id+"-"+item.name;
            
            th = th+'<th id="'+thId+'" rck-sortDirection="ASC" rck-gridIndex="'+item.name+'">'+item.display+'<i class="rck-grid-column-icon" style="float:right;display:none;" class="icon-chevron-up"></th>';
            
            _this._columns[item.name] = item.display;
            
            jQuery("#"+thId).live('click', function(){
                var icon = jQuery(this).find('i');
                
                jQuery(_this.jID()+" .rck-grid-column-icon").css('display','none');
                
                if(jQuery(icon).hasClass('icon-chevron-up')){
                    jQuery(icon).removeClass('icon-chevron-up').addClass('icon-chevron-down');
                    jQuery("#"+thId).attr('rck-sortDirection','DESC');
                }
                else{
                    jQuery(icon).removeClass('icon-chevron-down').addClass('icon-chevron-up');
                    jQuery("#"+thId).attr('rck-sortDirection','ASC');
                }
                
                jQuery(icon).css('display','block');
                
                _this.sortname = jQuery("#"+thId).attr('rck-gridIndex');
                _this.sortorder = jQuery("#"+thId).attr('rck-sortDirection');
                
                //sorting of result
                _this.sort(_this.sortname, _this.sortorder);
            });
            
        });
    }
    
    //have searchItems
    if(this.searchItems){
        input = '<input style="margin-bottom:0;" id='+iId+' name="'+iName+'" class="'+inputClass+'" type="text" placeholder="'+_this.searchButtonText+'">';
        btnSearch = '<button class="btn"><i class="icon-search"></i></button>';
        select = '<select id="'+sId+'" class="'+selectClass+'" name="'+sName+'" aria-controls="'+sId+'">';
        jQuery.each(_this.searchItems, function(i, item){
            select = select+'<option value="'+item.field+'">'+item.display+'</option>';
        });
        
        select = select+'</select>';
        
        search =  '<span style="float:right;">'+
                        input+
                        select+
                        btnSearch+
                  '</span> ';   
    }
//    return '<table style="width:100%;margin-bottom:0;" class="table table-bordered"><thead>'+
    return '<table style="width:100%;margin-bottom:0;" class="'+classes+'"><thead>'+
                '<tr>'+
                    '<th colspan="'+colspan+'">'+
                        '<span class="'+titleClass+'">'+this.title+'</span>'+search+
                    '</th>'+
                '</tr>'+
                '<tr>'+th+'</tr>'+
            '</thead></table>';
};

Grid.prototype.create = function(options){
    this.setOptions(options);
    
    
    
    var jRenderTo = "#"+this.renderTo;

    jQuery(jRenderTo).html(this.makeHtml());
    
    this.fixCellWidth(10);
    
//    if(this.autoLoad){
//        this._load(callback)
//    }
    
    
    
//    var elemWidth = jQuery(this.jID()).width();
//    var columnsWidth = this.columns.length*this._minTdWidth;
//    
//    var tdwidth = elemWidth/this.columns.length;
//    
//    if(!$.browser.msie){
//        jQuery(this.jID()+" table thead tr th").css('width', tdwidth);
//        jQuery(this.jID()+" table tbody tr td").css('width', tdwidth);
//
//        columnsWidth = tdwidth*this.columns.length+10;
//        jQuery(this.jID()).width(columnsWidth+"px");
//    }
//    
//    if(elemWidth < columnsWidth){
//        columnsWidth = columnsWidth+110;
//        jQuery(this.jID()).width(columnsWidth+"px");
//    }
}

Grid.prototype.fixCellWidth = function(extraPixels){
    var elemWidth = jQuery(this.jID()).width();
    var columnsWidth = this.columns.length*this._minTdWidth;
    var tdwidth = elemWidth/this.columns.length;
    
    var npx = 10;
    if(extraPixels) npx = extraPixels;
    
    if(!$.browser.msie){
        jQuery(this.jID()+" table thead tr th").css('width', tdwidth);
        jQuery(this.jID()+" table tbody tr td").css('width', tdwidth);

        columnsWidth = tdwidth*this.columns.length+npx;
        
        this._tdWidth = tdwidth;
        
        jQuery(this.jID()).width(columnsWidth+"px");
    }
    
    if(elemWidth < columnsWidth){
        columnsWidth = columnsWidth+110;
        jQuery(this.jID()).width(columnsWidth+"px");
    }
}

function Grid(options){
    this.create(options);
}
